package com.bw.gmall.realtime.tag;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.common.base.BaseApp;
import com.bw.gmall.realtime.common.bean.TradeSkuOrderBeanTag;
import com.bw.gmall.realtime.common.constant.Constant;
import com.bw.gmall.realtime.common.function.DimRichAsyncFunction;
import com.bw.gmall.realtime.common.function.DorisMapFunction;
import com.bw.gmall.realtime.common.util.*;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

public class DwsTradeSkuOrderWindowAsyncCacheRelTag extends BaseApp {
    public static void main(String[] args) {
        new DwsTradeSkuOrderWindowAsyncCacheRelTag().start(10038, 4, Constant.TOPIC_DWD_TRADE_ORDER_DETAIL, Constant.DWS_TRADE_SKU_ORDER_WINDOW);
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> kafkaSource) {
        // 1. 读取数据源
        // 2. 数据清洗
        SingleOutputStreamOperator<JSONObject> etlStream = kafkaSource.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                try {
                    // 因为有撤回流,所有要过滤
                    if (s != null) {
                        JSONObject jsonObject = JSON.parseObject(s);
                        String skuId = jsonObject.getString("sku_id");
                        Long ts = jsonObject.getLong("ts");
                        if (skuId != null && ts != null) {
                            jsonObject.put("ts", ts * 1000);
                            collector.collect(jsonObject);
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        // 3. 添加水位线
        SingleOutputStreamOperator<JSONObject> watermarksStream = etlStream.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3)).withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject jsonObject, long l) {
                return jsonObject.getLong("ts");
            }
        }));
        // 4.分组
        KeyedStream<JSONObject, String> keyedStream = watermarksStream.keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject jsonObject) throws Exception {
                // 不能以sku_id分组，会引起重复计算
                return jsonObject.getString("id");
            }
        });
        // 5.校正数据
        SingleOutputStreamOperator<TradeSkuOrderBeanTag> processStream = keyedStream.process(new KeyedProcessFunction<String, JSONObject, TradeSkuOrderBeanTag>() {

            private MapState<String, BigDecimal> mapState;

            @Override
            public void open(Configuration parameters) throws Exception {
                MapStateDescriptor<String, BigDecimal> stateDescriptor = new MapStateDescriptor<String, BigDecimal>("order_state", String.class, BigDecimal.class);
//                stateDescriptor.enableTimeToLive(StateTtlConfig.newBuilder(Time.seconds(30L)).build());
                mapState = getRuntimeContext().getMapState(stateDescriptor);
            }

            @Override
            public void processElement(JSONObject jsonObject, KeyedProcessFunction<String, JSONObject, TradeSkuOrderBeanTag>.Context context, Collector<TradeSkuOrderBeanTag> collector) throws Exception {
                BigDecimal splitTotalAmount = jsonObject.getBigDecimal("split_total_amount");
                BigDecimal splitActivityAmount = jsonObject.getBigDecimal("split_activity_amount");
                BigDecimal splitCouponAmount = jsonObject.getBigDecimal("split_coupon_amount");
                BigDecimal sku_num = jsonObject.getBigDecimal("sku_num");
                BigDecimal orderPrice = jsonObject.getBigDecimal("order_price");

                // 为了后面能关联用户维度
                String userId = jsonObject.getString("user_id");

                // 计算原始金额
                BigDecimal originalAmount = orderPrice.multiply(sku_num);

                // 取状态
                BigDecimal split_total_amount = mapState.get("splitTotalAmount");
                BigDecimal split_activity_amount = mapState.get("splitActivityAmount");
                BigDecimal split_coupon_amount = mapState.get("splitCouponAmount");
                BigDecimal original_amount = mapState.get("originalAmount");
                split_total_amount = split_total_amount == null ? new BigDecimal(0) : split_total_amount;
                split_activity_amount = split_activity_amount == null ? new BigDecimal(0) : split_activity_amount;
                split_coupon_amount = split_coupon_amount == null ? new BigDecimal(0) : split_coupon_amount;
                original_amount = original_amount == null ? new BigDecimal(0) : original_amount;

                String skuId = jsonObject.getString("sku_id");
                String skuName = jsonObject.getString("sku_name");
                String id = jsonObject.getString("id");
                Long ts = jsonObject.getLong("ts");
                collector.collect(TradeSkuOrderBeanTag.builder().userId(userId).skuId(skuId).orderDetailId(id).orderAmount(splitTotalAmount.subtract(split_total_amount)).originalAmount(originalAmount.subtract(original_amount)).activityReduceAmount(splitActivityAmount.subtract(split_activity_amount)).couponReduceAmount(splitCouponAmount.subtract(split_coupon_amount)).skuName(skuName).ts(ts).build());
                // 更新状态
                mapState.put("splitTotalAmount", splitTotalAmount);
                mapState.put("splitActivityAmount", splitActivityAmount);
                mapState.put("splitCouponAmount", splitCouponAmount);
                mapState.put("originalAmount", originalAmount);

            }
        });
        // 6.分组 开窗 聚合
        SingleOutputStreamOperator<TradeSkuOrderBeanTag> reduceStream = processStream.keyBy(new KeySelector<TradeSkuOrderBeanTag, String>() {
            @Override
            public String getKey(TradeSkuOrderBeanTag TradeSkuOrderBeanTag) throws Exception {
                return TradeSkuOrderBeanTag.getSkuId();
            }
        }).window(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10L))).reduce(new ReduceFunction<TradeSkuOrderBeanTag>() {
            @Override
            public TradeSkuOrderBeanTag reduce(TradeSkuOrderBeanTag value1, TradeSkuOrderBeanTag value2) throws Exception {
                value1.setOriginalAmount(value1.getOriginalAmount().add(value2.getOriginalAmount()));
                value1.setCouponReduceAmount(value1.getCouponReduceAmount().add(value2.getCouponReduceAmount()));
                value1.setActivityReduceAmount(value1.getActivityReduceAmount().add(value2.getActivityReduceAmount()));
                value1.setOrderAmount(value1.getOrderAmount().add(value2.getOrderAmount()));
                return value1;
            }
        }, new ProcessWindowFunction<TradeSkuOrderBeanTag, TradeSkuOrderBeanTag, String, TimeWindow>() {
            @Override
            public void process(String s, ProcessWindowFunction<TradeSkuOrderBeanTag, TradeSkuOrderBeanTag, String, TimeWindow>.Context context, Iterable<TradeSkuOrderBeanTag> iterable, Collector<TradeSkuOrderBeanTag> collector) throws Exception {
                TimeWindow window = context.window();
                long start = window.getStart();
                long end = window.getEnd();
                for (TradeSkuOrderBeanTag TradeSkuOrderBeanTag : iterable) {
                    TradeSkuOrderBeanTag.setStt(DateFormatUtil.tsToDateTime(start));
                    TradeSkuOrderBeanTag.setEdt(DateFormatUtil.tsToDateTime(end));
                    TradeSkuOrderBeanTag.setCurDate(DateFormatUtil.tsToDate(System.currentTimeMillis()));
                    collector.collect(TradeSkuOrderBeanTag);
                }
            }
        });

        // 关联用户
        SingleOutputStreamOperator<TradeSkuOrderBeanTag> dimStreamByUser = AsyncDataStream.unorderedWait(reduceStream, new DimRichAsyncFunction<TradeSkuOrderBeanTag>() {
            @Override
            public String getTable() {
                return "dim_user_info";
            }

            @Override
            public String getRowKey(TradeSkuOrderBeanTag TradeSkuOrderBeanTag) {
                return TradeSkuOrderBeanTag.getUserId();
            }

            @Override
            public void setDimInfo(TradeSkuOrderBeanTag tradeSkuOrderBeanTag,JSONObject dimUserInfo) {
                // 处理用户标签
                // 处理用户性别标签
                String gender = dimUserInfo.getString("gender");
                tradeSkuOrderBeanTag.setGender(gender);
                if ("F".equals(gender)){
                    tradeSkuOrderBeanTag.setUserGenderType("女");
                }else if ("M".equals(gender)){
                    tradeSkuOrderBeanTag.setUserGenderType("男");
                }else{
                    tradeSkuOrderBeanTag.setUserGenderType("未知");
                }
                // 用户手机号
                String phoneNum = dimUserInfo.getString("phone_num");
                String mobileBelong = MobileUtils.checkMobileBelong(phoneNum);
                String[] strs = mobileBelong.split(",");
                tradeSkuOrderBeanTag.setCarrier(strs[0]);
                tradeSkuOrderBeanTag.setCarrierName(strs[1]);

                // 用户邮箱
                String email = dimUserInfo.getString("email");
                if(email != null && !"".equals(email)){
                    String emailGrp = email.substring(email.indexOf("@") +  1 );
                    //
                    String emailChinese = EmailUtil.judgeEmail(emailGrp);
                    tradeSkuOrderBeanTag.setEmail(emailGrp);
                    tradeSkuOrderBeanTag.setEmailType(emailChinese);
                }
                // 用户年龄
                String birthday = dimUserInfo.getString("birthday");
                int age = AgeUtil.getAgeByBirthday(birthday);
                String[] ageType = AgeUtil.getAgeType(age);
                tradeSkuOrderBeanTag.setYearBaseType(ageType[0]);
                tradeSkuOrderBeanTag.setYearBaseName(ageType[1]);


            }
        }, 60, TimeUnit.SECONDS);
//        dimStreamByUser.print();


        // unorderedWait 无序
        // ordered有序
        // 关联sku
        SingleOutputStreamOperator<TradeSkuOrderBeanTag> dimStreamBySku = AsyncDataStream.unorderedWait(dimStreamByUser, new DimRichAsyncFunction<TradeSkuOrderBeanTag>() {
            @Override
            public String getTable() {
                return "dim_sku_info";
            }

            @Override
            public String getRowKey(TradeSkuOrderBeanTag TradeSkuOrderBeanTag) {
                return TradeSkuOrderBeanTag.getSkuId();
            }

            @Override
            public void setDimInfo(TradeSkuOrderBeanTag TradeSkuOrderBeanTag,JSONObject dimSkuInfo) {
                TradeSkuOrderBeanTag.setSpuId(dimSkuInfo.getString("spu_id"));
                TradeSkuOrderBeanTag.setTrademarkId(dimSkuInfo.getString("tm_id"));
                TradeSkuOrderBeanTag.setCategory3Id(dimSkuInfo.getString("category3_id"));
            }
        }, 60, TimeUnit.SECONDS);

        // 关联spu
        SingleOutputStreamOperator<TradeSkuOrderBeanTag> dimStreamBySpu = AsyncDataStream.unorderedWait(dimStreamBySku, new DimRichAsyncFunction<TradeSkuOrderBeanTag>() {
            @Override
            public String getTable() {
                return "dim_spu_info";
            }



            @Override
            public String getRowKey(TradeSkuOrderBeanTag TradeSkuOrderBeanTag) {
                return TradeSkuOrderBeanTag.getSpuId();
            }
            @Override
            public void setDimInfo(TradeSkuOrderBeanTag TradeSkuOrderBeanTag, JSONObject dimSkuInfo) {
                TradeSkuOrderBeanTag.setSpuName(dimSkuInfo.getString("spu_name"));
            }
        }, 60, TimeUnit.SECONDS);


        // 关联tm
        SingleOutputStreamOperator<TradeSkuOrderBeanTag> dimStreamByTm = AsyncDataStream.unorderedWait(dimStreamBySpu, new DimRichAsyncFunction<TradeSkuOrderBeanTag>() {
            @Override
            public String getTable() {
                return "dim_base_trademark";
            }

            @Override
            public String getRowKey(TradeSkuOrderBeanTag TradeSkuOrderBeanTag) {
                return TradeSkuOrderBeanTag.getTrademarkId();
            }

            @Override
            public void setDimInfo(TradeSkuOrderBeanTag TradeSkuOrderBeanTag, JSONObject dimSkuInfo) {
                TradeSkuOrderBeanTag.setTrademarkName(dimSkuInfo.getString("tm_name"));
            }
        }, 60, TimeUnit.SECONDS);

        // 关联c3

        SingleOutputStreamOperator<TradeSkuOrderBeanTag> dimStreamByC3 = AsyncDataStream.unorderedWait(dimStreamByTm, new DimRichAsyncFunction<TradeSkuOrderBeanTag>() {
            @Override
            public String getTable() {
                return "dim_base_category3";
            }

            @Override
            public String getRowKey(TradeSkuOrderBeanTag TradeSkuOrderBeanTag) {
                return TradeSkuOrderBeanTag.getCategory3Id();
            }

            @Override
            public void setDimInfo(TradeSkuOrderBeanTag TradeSkuOrderBeanTag, JSONObject dimSkuInfo) {
                TradeSkuOrderBeanTag.setCategory3Name(dimSkuInfo.getString("name"));
                TradeSkuOrderBeanTag.setCategory2Id(dimSkuInfo.getString("category2_id"));
            }
        }, 60, TimeUnit.SECONDS);

        // 关联c2
        SingleOutputStreamOperator<TradeSkuOrderBeanTag> dimStreamByC2 = AsyncDataStream.unorderedWait(dimStreamByC3, new DimRichAsyncFunction<TradeSkuOrderBeanTag>() {
            @Override
            public String getTable() {
                return "dim_base_category2";
            }

            @Override
            public String getRowKey(TradeSkuOrderBeanTag TradeSkuOrderBeanTag) {
                return TradeSkuOrderBeanTag.getCategory2Id();
            }

            @Override
            public void setDimInfo(TradeSkuOrderBeanTag TradeSkuOrderBeanTag, JSONObject dimSkuInfo) {
                TradeSkuOrderBeanTag.setCategory2Name(dimSkuInfo.getString("name"));
                TradeSkuOrderBeanTag.setCategory1Id(dimSkuInfo.getString("category1_id"));
            }
        }, 60, TimeUnit.SECONDS);

        SingleOutputStreamOperator<TradeSkuOrderBeanTag> dimStreamByC1 = AsyncDataStream.unorderedWait(dimStreamByC2, new DimRichAsyncFunction<TradeSkuOrderBeanTag>() {
            @Override
            public String getTable() {
                return "dim_base_category1";
            }

            @Override
            public String getRowKey(TradeSkuOrderBeanTag TradeSkuOrderBeanTag) {
                return TradeSkuOrderBeanTag.getCategory1Id();
            }

            @Override
            public void setDimInfo(TradeSkuOrderBeanTag TradeSkuOrderBeanTag, JSONObject dimSkuInfo) {
                TradeSkuOrderBeanTag.setCategory1Name(dimSkuInfo.getString("name"));
            }
        }, 60, TimeUnit.SECONDS);
//        // 写到doris
        dimStreamByC1.map(new DorisMapFunction<>()).sinkTo(FlinkSinkUtil.getDorisSink(Constant.DWS_TRADE_SKU_ORDER_USER_TAG_WINDOW));

    }
}
